# -*- coding: UTF-8 -*-
"""
@auth:buxiangjie
@date:2023/2/3 10:49
@describe: 使用模板生成html报告
"""

from jinja2 import Environment, FileSystemLoader
from util.run_case import RunCase
from pathlib import Path
from util.common import WindowPrint

import os
import shutil

def generate_html(obj: RunCase, window):
	path = Path(__file__).parent
	WindowPrint().print("初始化测试报告模板......")
	env = Environment(loader=FileSystemLoader(path))
	env.variable_start_string = "{{!"
	env.variable_end_string = "!}}"
	template = env.get_template("complates/index.html")
	window.refresh()
	WindowPrint().print("拷贝静态资源至输出目录......")
	if os.path.exists(path / "output"):
		shutil.rmtree(path / "output")
	# 将静态资源复制到输出目录下
	shutil.copytree(path / "complates" / "fonts", path / "output" / "fonts")
	shutil.copytree(path / "complates" / "static", path / "output" / "static")
	window.refresh()
	# 写入主页
	WindowPrint().print("渲染测试报告汇总html......")
	with open(path / "output" / "index.html", "w+", encoding="utf8") as index:
		content = template.render(
			summary=obj.summary,
			overview=obj.overview
		)
		index.write(content)
	window.refresh()
	# 写入用例详情
	WindowPrint().print("渲染测试结果详情html......")
	template = env.get_template("complates/case_detail_temp.html")
	for c in obj.final_case:
		with open(path / "output" / f"{c['case_id']}.html", "w+", encoding="utf8") as detail:
			content = template.render(
				case_detail=c
			)
			detail.write(content)
	window.refresh()
